from app.objectpools.father_ui_pool import Father_Ui_Pool

from loguru import logger


class Portal_Pool:  # 全局池 传送门类
    # 方便全局快速调用
    portals = {}


class Super_Object:
    def __init__(self, obj=None):
        import inspect
        self.obj = obj
        frame = inspect.currentframe().f_back
        filename = inspect.getframeinfo(frame).filename
        self.where = filename


class Ui_Pool(Father_Ui_Pool):
    def __init__(self, name):
        super().__init__()
        self.name = name
        self.pool = {}

    def set_objectByName(self, obj_name, obj):
        if type(obj) == Super_Object:
            logger.info(f"命名为{obj_name}的对象 在{obj.where}处被注册到{self.__class__.__name__}对象中")
        self.pool[obj_name] = obj

    def capacity(self):
        super(Ui_Pool, self).capacity()
        length = self.pool.__len__()
        return length

    def find_object_byName(self, name):
        if not name.strip():
            raise Exception(f"{name} 是无效的key值")
        try:
            super(Ui_Pool, self).find(name)
            get = self.pool[name]

            if type(get) == Super_Object:
                return get.obj
            return get

        except KeyError:
            error_message = f"你可能还没有注册'{name}'这个名字的对象！"
            raise Exception(error_message)

    def del_object_byName(self, name):
        try:
            del self.pool[name]

        except KeyError:
            logger.warning(f"名为{name}的对象已经删除过了")

    def change_a_and_b_byName(self, obj_a_name, obj_b_name):
        # 互换obj_a_name和obj_b_name所指的对象
        a = self.pool[obj_a_name]
        self.pool[obj_a_name] = self.pool[obj_b_name]
        self.pool[obj_b_name] = a
